package main

import (
	"context"
	"flag"
	"fmt"

	"os"
	"os/signal"
	"runtime"
	"sync"
	"syscall"
	"time"

	"starsine.cn/appTpl/cmn"
	. "starsine.cn/appTpl/cmn/defs"
	"starsine.cn/appTpl/svccenter/cmd"
	"starsine.cn/appTpl/svccenter/registry"
)

var signalsHdl = []os.Signal{os.Interrupt, syscall.SIGTERM}

func main() {
	flag.Parse()
	runtime.GOMAXPROCS(1)

	sigchan := make(chan os.Signal)
	signal.Notify(sigchan, signalsHdl...)

	ctxt := &AppContext{
		Wg:      &sync.WaitGroup{},
		SigChan: sigchan,
	}
	ctxt.Ctx, ctxt.Cancel = context.WithCancel(context.Background())
	go SignalHandler(sigchan, ctxt)

	cmn.Start(ctxt)

	cmd.Start(ctxt)

	registry.Start(ctxt)

	//main goroutine waiting group protect (delay 1 second to ensure wait group start work):
	time.Sleep(1 * time.Second)

	ctxt.Wg.Wait()

	finish()
	fmt.Println("main exit complete")
}

func finish() {
	cmn.End()
}

func SignalHandler(signalchan chan os.Signal, appContext *AppContext) {
	for {
		select {
		case sig := <-signalchan:
			fmt.Printf("receive signal (%s).", sig)
			appContext.Cancel()
			return
		}
	}
}
